package com.hzmall.controller.interceptor;

import com.hzmall.common.Const;
import com.hzmall.common.ServerResponse;
import com.hzmall.pojo.User;
import com.hzmall.util.CheckLoginUtil;
import com.hzmall.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.print.attribute.standard.MediaSize;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Slf4j
public class AuthorityInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler; //强转
        String methodName = handlerMethod.getMethod().getName();  //获取当前拦截器拦截的方法名称
        String className = handlerMethod.getBean().getClass().getSimpleName();  //获取当前拦截器拦截的方法的类名称
        StringBuilder sb = new StringBuilder();
        Map paraMap = request.getParameterMap();
        Iterator iterator = paraMap.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry entry = (Map.Entry) iterator.next();
            String key = (String) entry.getKey();
            String valueStr = StringUtils.EMPTY;
            Object object = entry.getValue(); //values返回的是String[]
            if (object instanceof String[]){
                String[] values = (String[]) object;
                valueStr = Arrays.toString(values);  // 数组转字符串
            }
           sb.append(key).append("=").append(valueStr);
        }
        log.info(sb.toString());
        //后台管理的login方法不需要判断是否登录，拦截器遇到该方法直接放行
        //返回true即为放行
        if (StringUtils.equals(methodName,"login") && StringUtils.equals(className,"UserBackendController")){
            log.info("拦截到login方法，此方法放行");
            return true;
        }
        User user = null;
        user = CheckLoginUtil.doCheckLogin(request);
        if (user == null || user.getRole() == Const.ROLE.ROLE_CUSTOMER){  //用户未登录或当前登录用户不是管理员,需要返回特定内容
            response.reset();
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json;charset=utf-8");
            PrintWriter printWriter = response.getWriter();
            //分情况进行处理，后期代码中有富文本上传工具，该工具需要的返回值比较特殊，需要特殊处理
            if (user == null){
                if (StringUtils.equals(className,"ProductBackendController") && StringUtils.equals(methodName,"richTextImgUpload")){
                    Map map = new HashMap();
                    map.put("success","false");
                    map.put("msg","请登录管理员账户");
                    printWriter.print(JsonUtil.obj2String(map));
                }else{
                    printWriter.print(JsonUtil.obj2String(ServerResponse.createByErrorMessage("用户未登录")));
                }
            }else {
                if (user.getRole() == Const.ROLE.ROLE_CUSTOMER) {
                    if (StringUtils.equals(className, "ProductBackendController") && StringUtils.equals(methodName, "richTextImgUpload")) {
                        Map map = new HashMap();
                        map.put("success", "false");
                        map.put("msg", "当前账户无权限进行操作");
                        printWriter.print(JsonUtil.obj2String(map));
                    } else {
                        printWriter.print(JsonUtil.obj2String(ServerResponse.createByErrorMessage("用户未登录")));
                    }
                }
            }
            printWriter.flush();
            printWriter.close();
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
